# 导入selenium工具
from selenium import webdriver
from lxml import etree
import time
class Huya(object):
	# 初始化
	def __init__(self):
		# 通过浏览器加载网页驱动
		self.driver = webdriver.PhantomJS()
		# 要统计的数据
		self.room_count = 0
		self.hot_count = 0

	# 执行爬虫
	def run(self):
		c = ""
		# 打开具体的网页
		# self.driver.get('https://www.huya.com/l')
		
		# 爬取相关的内容
		content = etree.HTML(self.driver.page_source)
		# 爬取房间的所有信息
		rooms = content.xpath('//li[@class="game-live-item"]')
		for room in rooms:
			# 房间名称
			tmp = room.xpath('./a[@class="title new-clickstat"]/text()')
			roomname = tmp[0]
			# 房间热度
			tmp = room.xpath('./span[@class="txt"]/span[@class="num"]/i[@class="js-num"]/text()')
			hot = tmp[0]
			# print('房间人气:', hot, ',房间名称:', roomname)
			c += '房间人气:'+ hot + ',房间名称:' + roomname + '\n'
			# 增加房间数量
			self.room_count += 1
			# 增加人气数量
			if hot[-1] == '万':
				hot = hot[:-1] # 38.6万 --- 38.6
				hot = int(float(hot) * 10000)
				self.hot_count += hot
			else:
				hot = int(hot)
				self.hot_count += hot
			
		# 输出结果
		c += '当前房间总数：' + str(self.room_count) + '\n' + '当前人气总数：' + str(self.hot_count)
		# print('当前房间总数：', self.room_count)
		# print('当前人气总数：', self.hot_count)
		return c
	# 测试代码 测试翻页的效果
	def test(self):

		# 打开具体的网页
		self.driver.get('https://www.huya.com/l')
		# 遍历每一页
		page = 0
		while True:
			time.sleep(0.5)
			page += 1
			ret = self.driver.page_source.find('laypage_next')
			if ret >= 0: # 非最后一页
				print('第' + str(page) + '页')
				c = self.run()
				self.writeInfo(content = c,filename = str(page))
			else:
				print('最后一页')
				break
		
			# 点击下一页按钮
			self.driver.find_element_by_class_name('laypage_next').click()
	def writeInfo(self,content,filename):
		filename = "第"+filename+"页.txt"
		f = open(filename, 'w', encoding='utf-8')
		f.write(content)
		f.close()
		
		
if __name__ == '__main__':
	huya = Huya()
	#huya.run()
	huya.test()

